#!/bin/bash

# Java 17环境配置脚本
echo "🔧 配置Java 17环境..."

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 检查当前Java版本
echo "当前Java版本:"
java -version

# 安装Java 17
echo "安装Java 17..."
if command -v brew &> /dev/null; then
    echo "使用Homebrew安装Java 17..."
    brew install openjdk@17
    
    # 创建符号链接
    sudo ln -sfn /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk
    
    # 配置环境变量
    echo 'export PATH="/opt/homebrew/opt/openjdk@17/bin:$PATH"' >> ~/.zshrc
    echo 'export JAVA_HOME="/opt/homebrew/opt/openjdk@17"' >> ~/.zshrc
    
    # 立即生效
    export PATH="/opt/homebrew/opt/openjdk@17/bin:$PATH"
    export JAVA_HOME="/opt/homebrew/opt/openjdk@17"
    
    echo -e "${GREEN}✅ Java 17安装完成${NC}"
    
    # 验证安装
    echo "验证Java版本:"
    java -version
    
    # 配置Maven使用Java 17
    if [ -f "~/.m2/settings.xml" ]; then
        echo "Maven配置已存在"
    else
        mkdir -p ~/.m2
        cat > ~/.m2/settings.xml << 'EOF'
<settings>
    <profiles>
        <profile>
            <id>jdk-17</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <maven.compiler.source>17</maven.compiler.source>
                <maven.compiler.target>17</maven.compiler.target>
            </properties>
        </profile>
    </profiles>
</settings>
EOF
    fi
    
    echo -e "${GREEN}✅ Java 17环境配置完成！${NC}"
    echo "请重新打开终端或运行: source ~/.zshrc"
    
else
    echo -e "${RED}请先安装Homebrew${NC}"
    echo "访问: https://brew.sh/"
fi